package com.bawei.module_live.ui

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseMVIFragment
import com.bawei.module_live.databinding.FragmentLiveBinding
import com.bawei.module_live.ui.adapter.LiveAdapter
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


/**
 * 直播列表页面Fragment
 * 
 * 功能特点：
 * 1. 垂直滑动直播列表 - 类似抖音的滑动体验
 * 2. 自动播放控制 - 只播放当前可见的视频
 * 3. 分页加载 - 支持无限滚动加载更多
 * 4. 红包动画 - 滑动时触发红包动画效果
 * 5. 性能优化 - 预加载、缓存管理、内存优化
 * 
 * 技术实现：
 * - PagerSnapHelper实现精确分页
 * - RecyclerView + LinearLayoutManager
 * - ExoPlayer视频播放
 * - 协程处理异步操作
 * - MVI架构状态管理
 */
class LiveFragment : BaseMVIFragment() {
    
    // ==================== 常量定义 ====================
    
    companion object {
        private const val TAG = "LiveFragment"
        private const val DEFAULT_PAGE_SIZE = 10
        private const val PRELOAD_THRESHOLD = 3 // 预加载阈值
    }
    
    // ==================== UI组件 ====================
    
    /**
     * ViewBinding实例
     */
    private var _binding: FragmentLiveBinding? = null
    private val binding get() = _binding!!
    
    /**
     * ViewModel实例
     */
    private val liveViewModel: LiveViewModel by viewModels()
    
    /**
     * 适配器和布局管理器
     */
    private lateinit var liveAdapter: LiveAdapter
    private lateinit var layoutManager: LinearLayoutManager
    
    // ==================== 状态管理 ====================
    
    /**
     * 分页状态管理
     */
    private var currentPage = 1
    private var isLoading = false
    private var hasMoreData = true
    private var isFirstLoad = true
    // 新增：只在首次进入页面时自动播放
    private var hasAutoPlayed = false
    // 新增：只在真正首次进入Fragment时自动播放一次
    private var hasEverAutoPlayed = false
    
    /**
     * 滚动状态管理
     */
    private var lastVisiblePosition = 0
    private var isUserScrolling = false
    
    // ==================== 生命周期方法 ====================
    
    override fun getFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentLiveBinding.inflate(inflater, container, false)
        // 提前初始化 liveAdapter，保证生命周期安全
        liveAdapter = LiveAdapter(
            context = requireContext(),
            lifecycleScope = lifecycleScope
        )
        return binding.root
    }

    override fun handleState() {

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG, "onViewCreated: 直播列表页面创建")
        
        // 初始化UI组件
        initViews()
        
        // 设置RecyclerView
        setupRecyclerView()
        
        // 设置分页助手
        setupSnapHelper()
        
        // 设置滚动监听
        setupScrollListener()
        
        // 设置状态监听
        setupStateObserver()
        
        // 延迟加载初始数据
        view.post {
            loadInitialData()
        }
        
        Log.d(TAG, "onViewCreated: 直播列表页面初始化完成")
    }
    
    override fun onResume() {
        super.onResume()
        // 只在首次进入Fragment时自动播放
        if (isVisible && !hasEverAutoPlayed && liveAdapter.itemCount > 0) {
            liveAdapter.playVideo(0)
            hasAutoPlayed = true
            hasEverAutoPlayed = true
        }
    }

    override fun onPause() {
        super.onPause()
        // Fragment 不可见时彻底释放所有播放器资源，防止切换 Fragment 后声音残留
        liveAdapter.releaseAllPlayers()
        hasAutoPlayed = false // 只重置本次自动播放标志，不重置 hasEverAutoPlayed
    }

    override fun onStop() {
        super.onStop()
        // 页面不可见时彻底释放所有播放器资源，防止切换到别的 Fragment 后声音残留
        liveAdapter.releaseAllPlayers()
        hasAutoPlayed = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d(TAG, "onDestroyView: 直播列表页面销毁")
        // 清理资源
        cleanupResources()
        // 彻底释放所有播放器资源，防止切换页面后声音残留
        if (::liveAdapter.isInitialized) {
            liveAdapter.releaseAllPlayers()
        }
        hasAutoPlayed = false
        // 清理ViewBinding，防止内存泄漏
        _binding = null
    }

    override fun lazyLoad() {
        loadInitialData()
    }

    override fun generateViewModel() {
        // 使用 viewModels() 委托，无需手动生成
    }
    
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            // Fragment 被隐藏时彻底释放所有播放器资源，防止切换后声音残留
            if (::liveAdapter.isInitialized) {
                liveAdapter.releaseAllPlayers()
            }
            hasAutoPlayed = false
        }
    }
    
    // ==================== 初始化方法 ====================
    
    /**
     * 初始化UI组件
     */
    private fun initViews() {
        with(binding) {
            // 错误重试按钮
            errorView.setOnClickListener {
                retryLoading()
            }
            
            // 空状态重试按钮
            emptyView.setOnClickListener {
                retryLoading()
            }
            // 这里可以初始化红包等其他自定义View
        }
    }
    
    /**
     * 设置RecyclerView
     */
    private fun setupRecyclerView() {
        layoutManager = LinearLayoutManager(requireContext()).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        
        binding.rvLiveCovers.apply {
            this.layoutManager = this@LiveFragment.layoutManager
            setHasFixedSize(true)
            itemAnimator = null // 禁用动画提升性能
            
            // 创建并配置适配器
            adapter = liveAdapter
        }
        liveAdapter.setOnPlayerStateChangeListener { position, isPlaying ->
            handlePlayerStateChange(position, isPlaying)
        }
        liveAdapter.setOnEnterLiveRoomListener { liveData, position ->
            handleEnterLiveRoom(liveData, position)
        }
    }
    
    /**
     * 设置分页助手
     */
    private fun setupSnapHelper() {
        val snapHelper = PagerSnapHelper()
        snapHelper.attachToRecyclerView(binding.rvLiveCovers)
        
        // 监听对齐位置变化 - 通过滚动监听实现
        // 实际的 snap 位置检测在 setupScrollListener 中处理
    }
    
    /**
     * 设置滚动监听
     */
    private fun setupScrollListener() {
        binding.rvLiveCovers.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                isUserScrolling = newState == RecyclerView.SCROLL_STATE_DRAGGING
                
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        // 滚动停止时，确保当前项开始播放
                        val currentPosition = layoutManager.findFirstCompletelyVisibleItemPosition()
                        if (currentPosition != RecyclerView.NO_POSITION) {
                            handleSnapPositionChange(currentPosition)
                        }
                        // 停止红包动画
                        // binding.redPacketWidget.onScrollStop() // This line was removed as per the new_code
                        Log.d(TAG, "直播列表停止滑动，红包动画停止")
                    }
                    
                    // RecyclerView.SCROLL_STATE_DRAGGING -> { // This block was removed as per the new_code
                    //     // 用户开始滚动时，暂停所有播放
                    //     liveAdapter.pauseAllPlayers()
                    //     // 开始红包动画
                    //     binding.redPacketWidget.onScrollStart()
                    //     Log.d(TAG, "直播列表开始滑动，红包动画开始")
                    // }
                    
                    // RecyclerView.SCROLL_STATE_SETTLING -> { // This block was removed as per the new_code
                    //     // 惯性滑动时，继续红包动画
                    //     binding.redPacketWidget.onScrollStart()
                    //     Log.d(TAG, "直播列表惯性滑动，红包动画继续")
                    // }
                }
            }
            
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                
                // 检查是否需要加载更多
                checkLoadMore(dy)
            }
        })
    }
    
    /**
     * 设置状态监听器
     */
    private fun setupStateObserver() {
        lifecycleScope.launch {
            liveViewModel.liveState.collectLatest { state ->
                handleStateChange(state)
            }
        }
    }
    
    // ==================== 数据加载方法 ====================
    
    /**
     * 加载初始数据
     */
    private fun loadInitialData() {
        Log.d(TAG, "loadInitialData: 开始加载初始数据")
        
        if (isFirstLoad) {
            isFirstLoad = false
            currentPage = 1
            hasMoreData = true
            liveAdapter.clearData()
        }
        
        loadLiveList()
    }
    
    /**
     * 加载直播列表
     */
    private fun loadLiveList() {
        if (isLoading || !hasMoreData) return
        
        Log.d(TAG, "loadLiveList: 加载第${currentPage}页数据")
        
        isLoading = true
        liveViewModel.sendIntent(LiveIntent.FetchLiveListIntent(currentPage, DEFAULT_PAGE_SIZE))
    }
    
    /**
     * 重试加载
     */
    private fun retryLoading() {
        Log.d(TAG, "retryLoading: 重试加载数据")
        
        currentPage = 1
        hasMoreData = true
        isLoading = false
        liveAdapter.clearData()
        loadLiveList()
    }
    
    // ==================== 状态处理方法 ====================
    
    /**
     * 处理状态变化
     */
    private fun handleStateChange(state: LiveState) {
        when (state) {
            LiveState.Init -> {
                // 初始状态，不显示任何UI
            }
            
            LiveState.Loading -> {
                if (currentPage == 1) {
                    // 首次加载显示加载状态
                    showLoadingState()
                }
            }
            
            is LiveState.LiveListSuccess -> {
                handleLiveListSuccess(state.liveList)
            }
            
            is LiveState.Error -> {
                handleError(state.errorMsg)
            }
            
            else -> {
                // 其他状态暂不处理
            }
        }
    }
    
    /**
     * 处理直播列表成功
     */
    private fun handleLiveListSuccess(liveList: List<com.bawei.module_live.data.LiveData>) {
        Log.d(TAG, "handleLiveListSuccess: 获取到${liveList.size}条数据")
        
        isLoading = false
        
        if (liveList.isEmpty()) {
            if (currentPage == 1) {
                // 第一页没有数据，显示空状态
                showEmptyState()
            } else {
                // 后续页没有数据，标记没有更多数据
                hasMoreData = false
            }
        } else {
            // 有数据，添加到适配器
            liveAdapter.addData(liveList)
            currentPage++
            
            // 如果返回的数据少于请求的数量，说明没有更多数据了
            if (liveList.size < DEFAULT_PAGE_SIZE) {
                hasMoreData = false
            }
            
            // 隐藏加载状态
            hideLoadingState()
            // 移除自动播放逻辑，改为 onResume 控制
        }
    }
    
    /**
     * 处理错误状态
     */
    private fun handleError(errorMsg: String) {
        Log.e(TAG, "handleError: $errorMsg")
        
        isLoading = false
        
        if (currentPage == 1) {
            // 第一页加载失败，显示错误状态
            showErrorState(errorMsg)
        } else {
            // 后续页加载失败，显示Toast提示
            showToast("加载失败：$errorMsg")
        }
    }
    
    // ==================== UI状态管理 ====================
    
    /**
     * 显示加载状态
     */
    private fun showLoadingState() {
        with(binding) {
            loadingView.isVisible = true
            errorView.isVisible = false
            emptyView.isVisible = false
            rvLiveCovers.isVisible = false
        }
    }
    
    /**
     * 隐藏加载状态
     */
    private fun hideLoadingState() {
        with(binding) {
            loadingView.isVisible = false
            errorView.isVisible = false
            emptyView.isVisible = false
            rvLiveCovers.isVisible = true
        }
    }
    
    /**
     * 显示错误状态
     */
    private fun showErrorState(errorMsg: String) {
        with(binding) {
            loadingView.isVisible = false
            errorView.isVisible = true
            emptyView.isVisible = false
            rvLiveCovers.isVisible = false
        }
    }
    
    /**
     * 显示空状态
     */
    private fun showEmptyState() {
        with(binding) {
            loadingView.isVisible = false
            errorView.isVisible = false
            emptyView.isVisible = true
            rvLiveCovers.isVisible = false
        }
    }
    
    // ==================== 事件处理方法 ====================
    
    /**
     * 处理播放器状态变化
     */
    private fun handlePlayerStateChange(position: Int, isPlaying: Boolean) {
        Log.d(TAG, "handlePlayerStateChange: position=$position, isPlaying=$isPlaying")
        
        // 只播放当前可见的视频
        val currentVisiblePosition = layoutManager.findFirstCompletelyVisibleItemPosition()
        
        if (position == currentVisiblePosition) {
            if (isPlaying) {
                liveAdapter.playVideo(position)
            } else {
                liveAdapter.pauseVideo(position)
            }
        } else {
            // 不是当前可见的视频，暂停播放
            liveAdapter.pauseVideo(position)
        }
    }
    
    /**
     * 处理进入直播间
     */
    private fun handleEnterLiveRoom(liveData: com.bawei.module_live.data.LiveData, position: Int) {
        // 进入直播间前，彻底释放所有播放器，防止声音残留
        liveAdapter.releaseAllPlayers()
        // 跳转到直播间详情页
        ARouter.getInstance()
            .build(Router.Ui.LIVE_DETAIL_ACTIVITY)
            .withSerializable("live_data", liveData)
            .navigation()
    }
    
    /**
     * 处理分页位置变化
     */
    private fun handleSnapPositionChange(position: Int) {
        if (position != lastVisiblePosition) {
            Log.d(TAG, "handleSnapPositionChange: 位置变化 $lastVisiblePosition -> $position")
            
            // 暂停上一个视频
            if (lastVisiblePosition >= 0 && lastVisiblePosition < liveAdapter.itemCount) {
                liveAdapter.pauseVideo(lastVisiblePosition)
            }
            
            // 播放当前视频
            if (position >= 0 && position < liveAdapter.itemCount) {
                liveAdapter.playVideo(position)
            }
            
            lastVisiblePosition = position
            
            // 检查是否需要预加载
            checkPreload(position)
        }
    }
    
    // ==================== 辅助方法 ====================
    
    /**
     * 检查是否需要加载更多
     */
    private fun checkLoadMore(dy: Int) {
        if (dy > 0 && !isLoading && hasMoreData) {
            val visibleItemCount = layoutManager.childCount
            val totalItemCount = layoutManager.itemCount
            val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
            
            // 当剩余可见项少于阈值时，开始加载更多
            if (firstVisibleItemPosition + visibleItemCount >= totalItemCount - PRELOAD_THRESHOLD) {
                loadLiveList()
            }
        }
    }
    
    /**
     * 检查是否需要预加载
     */
    private fun checkPreload(currentPosition: Int) {
        // 当接近列表末尾时，预加载下一页数据
        if (currentPosition >= liveAdapter.itemCount - PRELOAD_THRESHOLD && hasMoreData && !isLoading) {
            loadLiveList()
        }
    }
    
    /**
     * 清理资源
     */
    private fun cleanupResources() {
        // 暂停所有播放器
        // liveAdapter.pauseAllPlayers() // This line was removed as per the new_code
        
        // 重置状态
        currentPage = 1
        isLoading = false
        hasMoreData = true
        isFirstLoad = true
        lastVisiblePosition = 0
        isUserScrolling = false
    }

    private fun showToast(msg: String) {
        android.widget.Toast.makeText(requireContext(), msg, android.widget.Toast.LENGTH_SHORT).show()
    }

    // 供外部（如 MainActivity）主动调用，彻底释放播放器并重置自动播放标志
    fun releaseAllPlayersSafe() {
        if (::liveAdapter.isInitialized) {
            liveAdapter.releaseAllPlayers()
        }
        hasAutoPlayed = false
    }

    // 供外部（如 MainActivity）主动调用，静音所有播放器
    fun muteAllPlayersSafe() {
        if (::liveAdapter.isInitialized) {
            liveAdapter.muteAllPlayers()
        }
    }
}